﻿
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TianYuan.Data.Dapper.Uow
{
    /// <summary>
    /// 工作单元
    /// </summary>
    public class UnitOfWork : IUnitOfWork
    {
        /// <summary>
        /// 当前工作单元的上下文
        /// </summary>
        private IDbContext _Currentontext { get; }

        /// <summary>
        /// Creates new unit of work instance, beginning a new transaction to the database.
        /// </summary>
        /// <param name="context">The context object.</param>
        public UnitOfWork(IDbContext context)
        {
            _Currentontext = context;
        }

        /// <summary>
        /// BeginTransaction
        /// </summary>
        public void BeginTransaction()
        {
            if (!_Currentontext.HasActiveTransaction)
            {
                // begins transaction
                _Currentontext.BeginTransaction();
            }
        }

        /// <summary>
        /// Save changes into context.
        /// </summary>
        public void Commit()
        {
            if (!_Currentontext.HasActiveTransaction)
            {
                throw new InvalidOperationException("Transaction have already been commited or disposed.");
            }
            // commits transation
            _Currentontext.Commit();
        }
        [Obsolete("Please use Rollback() ")]
        public void Dispose()
        {
            if (_Currentontext.HasActiveTransaction)
            {
                // rollback transaction
                _Currentontext.Rollback();
            }
        }
        /// <summary>
        /// Rollback
        /// </summary>
        public void Rollback()
        {
            if (_Currentontext.HasActiveTransaction)
            {
                // rollback transaction
                _Currentontext.Rollback();
            }
        }
        
    }
}
